package com.demo.controller;

import com.demo.common.Page;
import com.demo.common.message.BaseResponse;
import com.demo.common.util.StringUtil;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by jie_r on 2016/11/27.
 */
public class BaseController {
    public static final String SUCCESS = "0";
    public static final String FAILED = "1";
    public static final String FAULT = "-1";

    protected HttpSession session;

    // 设置页数
    protected Page page;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request) {
        this.session = request.getSession();
        this.setPage(request.getParameter("curPage"),
                request.getParameter("pageSize"));
        this.init(request);

    }

    private void init(HttpServletRequest request) {
        String keyword = request.getParameter("keyword");
        if (StringUtil.isNotEmpty(keyword)) {
            keyword = "%" + keyword + "%";
        }
        request.setAttribute("keyword", keyword);
    }

    /**
     * 设置page对象
     */
    private void setPage(String curPage, String pageSize) {
        this.page = new Page(curPage, pageSize);
    }

    public BaseResponse toError(Object data) throws Exception {
        return new BaseResponse(FAILED, data);
    }

    public BaseResponse toError(String message, Object data) throws Exception {
        return new BaseResponse(FAILED, message, data);
    }

    public BaseResponse toSuccess(Object data) throws Exception {
        return new BaseResponse(SUCCESS, data);
    }

    public BaseResponse toSuccess(String message, Object data) throws Exception {
        return new BaseResponse(SUCCESS, message, data);
    }
}
